package com.jh.notice.service;

import java.io.IOException;
import java.net.URI;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import cn.jh.common.utils.CommonsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.jh.notice.business.SmsSendBusiness;
import com.jh.notice.pojo.SMSRecord;
import com.jh.notice.util.NoticeConstants;
import com.jh.notice.util.Util;

import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;
import net.sf.json.JSONObject;


@Controller
@EnableAutoConfiguration
public class SmsSendService {


	private static final Logger LOG = LoggerFactory.getLogger(SmsSendService.class);

	@Autowired
	private SmsSendBusiness smsSendBusiness;

	@Autowired
	private Util util;


	@Value("${jh.keyPlan}")
	private   String keyPlan;

	/**发送短信*/
	@RequestMapping(method=RequestMethod.GET,value="/v1.0/notice/sms/send")
	public @ResponseBody Object sendMsg(HttpServletRequest request,
										@RequestParam(value = "phone") String phone,
										@RequestParam(value = "brand_id", defaultValue = "1", required=false) long brandid,
										@RequestParam(value = "type",required=true) int type){
		Map<String,Object> map = new HashMap<>();

		LOG.info("=====type:" + type);
		String ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-ipAddress");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-ipAddress");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
		}

		int sendCount = smsSendBusiness.findCountByIpAddress(ipAddress);

		if(sendCount > 100){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "您的操作过于频繁,请明天再试!");
			return map;
		}

		Random random = new Random();
		int x = random.nextInt(899999);
		x = x+100000;
		Map params  = new HashMap<String, String>();
		params.put("phone", phone);
		params.put("code", x+"");
		params.put("type", type+"");
		/**
		 * 获取通道信息
		 * *URL：/v1.0/user/brand/query/id
		 * **/
		RestTemplate restTemplate=new RestTemplate();
		URI uri = util.getServiceUrl("user", "error url request!");
		String url = uri.toString() + "/v1.0/user/brand/query/id?brand_id="+brandid;
		String resultStr = restTemplate.getForObject(url,  String.class);
		JSONObject jsonObject =  JSONObject.fromObject(resultStr);
		JSONObject brand=jsonObject.getJSONObject("result");
		String  tpl_id=brand.getString("tplid");

		/**
		 * 获取贴牌对应的key
		 */
		LOG.info("keyPlan===============================进来"+keyPlan);
		RestTemplate restTemplates=new RestTemplate();
		URI uris = util.getServiceUrl("user", "error url request!");
		String urls = uris.toString() + "/v1.0/user/brand/query/jh/key?brand_id="+brandid+"&keyPlan="+keyPlan;
		String results = restTemplates.getForObject(urls, String.class);
		JSONObject jsonObject1 = JSONObject.fromObject(results);
		JSONObject res = jsonObject1.getJSONObject("result");
		String jhKey = res.getString("jhKey");
		LOG.info("jhKey==============================="+jhKey);
		SMSRecord smsRecord = smsSendBusiness.sendSmsMessage(phone,tpl_id, params,ipAddress,jhKey,type);
		return CommonsUtil.returnSuccess(phone);
	}

	/**获取验证码**/
	@RequestMapping(method=RequestMethod.GET,value="/v1.0/notice/sms/vericode")
	public @ResponseBody Object queryVericode(HttpServletRequest request, @RequestParam(value = "phone") String phone){

		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT, smsSendBusiness.querySmscodeByPhone(phone));
		//map.put(CommonConstants.RESULT, "888888");
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		return map;
	}

	/**获取验证码场景类型 付环宇2018.08.13**/
	@RequestMapping(method=RequestMethod.GET,value="/v1.0/notice/sms/vericodetype")
	public @ResponseBody Object queryVericodeType(HttpServletRequest request, @RequestParam(value = "phone") String phone){
		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT, smsSendBusiness.querySmscodeTypeByPhone(phone));		//新增获取type
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		return map;
	}


	/**分页获取*/
	@RequestMapping(method=RequestMethod.GET,value="/v1.0/notice/sms/query")
	public @ResponseBody Object addFans(HttpServletRequest request,
										@RequestParam(value = "page", defaultValue = "0", required = false) int page,
										@RequestParam(value = "size", defaultValue = "20", required = false) int size,
										@RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
										@RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty,
										@RequestParam(value = "phone",  required = false) String phone,
										@RequestParam(value = "startTime",  required = false) String startTime,
										@RequestParam(value = "endTime",  required = false) String endTime) throws IOException{

		Map map = new HashMap();
		Date startDate = null;
		Date endDate = null;

		if(startTime == null || startTime.equalsIgnoreCase("")){
			if(endTime !=null && !endTime.equalsIgnoreCase("")){
				map.put(CommonConstants.RESP_CODE, NoticeConstants.ERROR_PARAM);
				map.put(CommonConstants.RESP_MESSAGE, "参数错误");
				return map;
			}
		}else{
			startDate = DateUtil.getDateFromStr(startTime);
			if(endTime !=null && !endTime.equalsIgnoreCase("")){
				endDate = DateUtil.getDateFromStr(endTime);
			}
		}

		Pageable pageable = new PageRequest(page, size, new Sort(direction,sortProperty));

		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, smsSendBusiness.findSmsRecord(pageable, phone, startDate, endDate));
		return map;
	}

}
